package br.com.nrti.still.dao;

import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import br.com.nrti.still.Application;
import br.com.nrti.still.ButtonMsg;
import br.com.nrti.still.Mensagens;

public class DataHelper {
	private static final String DATABASE_NAME = "userCadDB.db";
	private static final int DATABASE_VERSION = 1;

	public static NROpenHelper openHelper;
	public static SQLiteDatabase dataBase;
	private static Context context;

	public static void connect(Context context) {
		DataHelper.context = context;
		try {
			if (openHelper == null)
				openHelper = new NROpenHelper(DataHelper.context,
						DATABASE_NAME, DATABASE_VERSION);

			if (dataBase != null) {
				if (dataBase.isOpen())
					dataBase.close();
			}

			dataBase = openHelper.getWritableDatabase();
		} catch (Exception e) {
			e.printStackTrace();
			ButtonMsg btOK = new ButtonMsg("OK",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							System.exit(0);
						}
					});
			btOK.setTipo(DialogInterface.BUTTON_POSITIVE);
			Mensagens.showMessage(
					"Cadastro de Usuários",
					"Erro ao iniciar conexão com banco de dados:\n"
							+ e.getMessage(), new ButtonMsg[] { btOK }).show();
		}
	}

	public static SQLiteDatabase getDB() {
		if (dataBase == null || !dataBase.isOpen()) {
			connect(Application.appContext);
		}

		return dataBase;
	}
}
